package co.com.javeriana.aes.oms.common.service;

import co.com.javeriana.aes.oms.common.entity.Campaign;
import java.util.List;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Jonathan Fernandez <jonathan.fvargas@gmail.com>
 */
@Local (CommonServiceLocal.class)
@Stateless (name = "CommonService" , mappedName = "ejb/CommonService")
public class CommonService implements CommonServiceLocal {
    
    @PersistenceContext(unitName="OMS-PU")
    private EntityManager em;
    
    // <editor-fold defaultstate="collapsed" desc="CRUD Campaigns">
    
    /**
     * t
     * @param campaign
     * @throws Exception 
     */
    @Override
    public void createCampaign(Campaign campaign)throws Exception{
        
        try {
            
            em.persist(campaign);
            em.flush();
            
        } catch (Exception e) {
            throw e;
        }
    }

    @Override
    public void deleteCampaign(Campaign campaign) throws Exception{
    
        try {
        
            em.remove(em.contains(campaign) ? campaign : em.merge(campaign));
            em.flush();
            
        } catch (Exception e) {
            throw e;
        
        }
    
    }
    
    
    

    @Override
    public Campaign getCampaign(Long id) throws Exception{

        Campaign c = null;
        try {
            c = em.find(Campaign.class, id);
        } catch (Exception e) {
            throw e;
        }

        return c;
    }
    
    @Override
    public List<Campaign> getCampaigns() {

        List<Campaign> campaigns = null;

        try {
            Query data = em.createNamedQuery("Campaign.findAll");
            campaigns = data.getResultList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return campaigns;
    }

    @Override
    public void updateCampaign(Campaign campaign) throws Exception{
        
        try {
            em.merge(campaign);
            em.flush();
        } catch (Exception e) {
            throw e;
        }
        
    }
    
    // </editor-fold>

    
}
